package com.zkingsoft.rhi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkingsoft.rhi.entity.*;
import com.zkingsoft.rhi.handler.Result;
import com.zkingsoft.rhi.mapper.ImmovableHistoricalRelicsMapper;
import com.zkingsoft.rhi.mapper.MovableHistoricalRelicsMapper;
import com.zkingsoft.rhi.service.ImmovableHistoricalRelicsPublicationService;
import com.zkingsoft.rhi.service.StateOwnedUnitsService;
import com.zkingsoft.rhi.utils.ExcelUtils;
import com.zkingsoft.rhi.utils.MyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "excel导入导出")
@Slf4j
@RestController
@RequestMapping("/excel")

public class ExcelController {

    @Autowired
    ImmovableHistoricalRelicsMapper ihrm;

    @Autowired
    MovableHistoricalRelicsMapper mhrm;

    @Autowired
    StateOwnedUnitsService sous;

    @Autowired
    ImmovableHistoricalRelicsPublicationService ihrps;

    @Autowired
    MyUtils myUtils;


    /**
     * @author xieguo
     * 功能描述：不可移动文物excel导出
     * @param request
     * @param response
     * @return void
     * @date 2020/11/9 13:59
     */
    @ApiOperation(value = "分不同的区导出不同的不可移动文物")
    @GetMapping("/exportImmovableExcel")
    public void exportImmovableExcel(HttpServletRequest request,HttpServletResponse response){
        List<ExportImmovableHistoricalRelics> list = ihrm.queryAll();
        exportHandle(request,response,list);
    }


    @ApiOperation(value = "通过id进行导出")
    @GetMapping("/exportImmovableExcelById")
    public void exportImmovableExcelById(HttpServletRequest request,HttpServletResponse response){
        String ids = request.getParameter("ids");
        List<Integer> idsList = myUtils.handleIds(ids);
        List<ExportImmovableHistoricalRelics> list = ihrm.queryById(idsList);
        exportHandle(request,response,list);
    }


    /**
     * @author xieguo
     * 功能描述：导出不可移动文物excel方法抽取
     * @param request
     * @param response
     * @param list
     * @return void
     * @date 2020/11/24 15:59
     */
    public void exportHandle(HttpServletRequest request,HttpServletResponse response,List<ExportImmovableHistoricalRelics> list){
        Map<String, List<ExportImmovableHistoricalRelics>> resultList = list.stream().collect(Collectors.groupingBy(ExportImmovableHistoricalRelics::getArea));

        resultList.forEach((key,value)->{
            int exportId=0;
            for (ExportImmovableHistoricalRelics eihr : value) {
                exportId++;
                eihr.setExportId(exportId);
            }
        });

        resultList.forEach((key,value)->{
            value.forEach(data->{
                data.setArea("长沙市"+data.getArea());
            });
        });

        ExcelUtils.writeExcelGroup(request,response,resultList,ExportImmovableHistoricalRelics.class);
    }


    /**
     * @author xieguo
     * 功能描述：不可移动文物详细excel导出
     * @param request
     * @param response
     * @return void
     * @date 2020/11/18 13:57
     */
    @ApiOperation(value = "分不同的区导出不同的详细不可移动文物")
    @GetMapping("/exportDetailedImmovableExcel")
    public void exportDetailedImmovableExcel(HttpServletRequest request,HttpServletResponse response){
        List<ExportDetailedImmovableHistoricalRelics> list = ihrm.queryDetailedAll();
        exportDetailedHandle(request,response,list);
    }

    @ApiOperation(value = "通过id进行详细导出")
    @GetMapping("/exportDetailedImmovableExcelById")
    public void exportDetailedImmovableExcelById(HttpServletRequest request,HttpServletResponse response){
        String ids = request.getParameter("ids");
        List<Integer> idsList = myUtils.handleIds(ids);
        List<ExportDetailedImmovableHistoricalRelics> list = ihrm.queryDetailedById(idsList);
        exportDetailedHandle(request,response,list);
    }


    /**
     * @author xieguo
     * 功能描述:导出详细不可移动文物excel方法抽取
     * @param request
     * @param response
     * @param list
     * @return void
     * @date 2020/11/24 15:54
     */
    public void exportDetailedHandle(HttpServletRequest request,HttpServletResponse response,List<ExportDetailedImmovableHistoricalRelics> list){
        Map<String, List<ExportDetailedImmovableHistoricalRelics>> resultList = list.stream().collect(Collectors.groupingBy(ExportDetailedImmovableHistoricalRelics::getArea));

        resultList.forEach((key,value)->{
            int exportId=0;
            for (ExportDetailedImmovableHistoricalRelics edihr : value) {
                exportId++;
                edihr.setExportId(exportId);
            }
        });

        ExcelUtils.writeExcelGroup(request,response,resultList,ExportDetailedImmovableHistoricalRelics.class);
    }



    /**
     * @author xieguo
     * 功能描述：可移动文物excel导出
     * @param request
     * @param response
     * @return void
     * @date 2020/11/10 11:17
     */
    @ApiOperation(value = "可移动文物excel导出",notes = "需要传入的参数示例 fileName=导出测试.xls或者fileName=导出测试.xlsx")
    @GetMapping("/exportMovableExcel")
    public void exportMovableExcel(HttpServletRequest request,HttpServletResponse response){
        String s = request.getParameter("souId");
        Integer souId = new Integer(s);
        List<ExportMovableHistoricalRelics> list = mhrm.queryBySouId(souId);
        Integer exportId=0;
        for (int i = 0; i <list.size() ; i++) {
            exportId++;
            list.get(i).setExportId(exportId);
        }

        StateOwnedUnits sou = sous.getById(souId);
        long t1=System.currentTimeMillis();
        ExcelUtils.writeExcel(request,response,list,ExportMovableHistoricalRelics.class,"exportMovableExcel",sou);
        long t2=System.currentTimeMillis();
        System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
    }

    /**
     * @author xieguo
     * 功能描述：可移动文物的excel导入，支持去重，和数据更新
     * @param file
     * @return com.alibaba.fastjson.JSONObject
     * @date 2020/11/9 21:54
     */
    @ApiOperation(value = "可移动文物excel导入")
    @PostMapping("/readMovableExcel")
    public JSONObject readMovableExcel(@RequestBody MultipartFile file){
        long t1 = System.currentTimeMillis();
        log.info("上传的文件："+file);
        //文件数据读入的集合
        List<MovableHistoricalRelics> list = ExcelUtils.readExcel("readMovableExcel", MovableHistoricalRelics.class, file);

        // 获取集合对应的迭代器，用来遍历集合中的元素的。
//        list.removeIf(next -> null==next.getRegistrationNumber());

        for (int i = 0; i <list.size() ; i++) {
            if (null==list.get(i).getRegistrationNumber()){
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"文物编码不能为空");
            }
        }

        StateOwnedUnits stateOwnedUnits = new StateOwnedUnits();

        QueryWrapper<StateOwnedUnits> soqw = new QueryWrapper<>();
        soqw.eq("number",ExcelUtils.number);
        StateOwnedUnits oldSou = sous.getOne(soqw);

        if (ObjectUtil.isEmpty(oldSou)){
            stateOwnedUnits.setNumber(ExcelUtils.number);
            stateOwnedUnits.setName(ExcelUtils.name);
            stateOwnedUnits.setAddress(ExcelUtils.address);
            sous.save(stateOwnedUnits);
            for (int i = 0; i <list.size() ; i++) {
                list.get(i).setSouId(stateOwnedUnits.getId());
            }
        }else {
            for (int i = 0; i <list.size() ; i++) {
                list.get(i).setSouId(oldSou.getId());
            }
        }

//        System.out.println("list=======================>"+list.toString());
//        System.out.println("sizeBefore========================>"+list.size());
        //数据库里面ImmovableHistoricalRelics表的集合
        List<MovableHistoricalRelics> relicsList = mhrm.selectList(null);
//        System.out.println("relicsList========================>"+relicsList.size());
        //文件数据重复数据的集合
        List<MovableHistoricalRelics> repeatData = new ArrayList<>();
        //文件重复数据更新的集合
        List<MovableHistoricalRelics> updateData = new ArrayList<>();

        //俩重循环筛选重复数据
        for (int i = 0; i <list.size() ; i++) {

            for (int j = 0; j <relicsList.size() ; j++) {
                String number = list.get(i).getRegistrationNumber();
                String sqlNumber = relicsList.get(j).getRegistrationNumber();
                if (number.equals(sqlNumber)){
                    repeatData.add(list.get(i));
                    updateData.add(relicsList.get(j));
                }
            }
        }

//        System.out.println(repeatData.size()+"==========="+updateData.size());

//        把录入的数据放入带有id的数据里面
        for (int i = 0; i <updateData.size() ; i++) {
            updateData.get(i).setName(repeatData.get(i).getName());
            updateData.get(i).setRegistrationNumber(repeatData.get(i).getRegistrationNumber());
            updateData.get(i).setAmount(repeatData.get(i).getAmount());
            updateData.get(i).setIsShow(repeatData.get(i).getIsShow());
            updateData.get(i).setLevel(repeatData.get(i).getLevel());
            updateData.get(i).setSouId(repeatData.get(i).getSouId());
        }

//        System.out.println("repeatData=======================>"+repeatData.toString());
//        System.out.println("updateData=======================>"+updateData.toString());
        if (!updateData.isEmpty()){
            mhrm.batchUpdate(updateData);
        }

//        System.out.println("updateData===================>"+updateData.toString());
//        System.out.println("updateDataSize===================>"+updateData.size());

        list.removeAll(repeatData);

        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));

        if (list.isEmpty()){
            return Result.setResultByCodeAndMsg(Result.STATUS_SUCCESS,"数据已更新");
        }else {
            int i = mhrm.batchInsert(list);

            if (i>0){
                return Result.setResultByCodeAndMsg(Result.STATUS_SUCCESS,"上传成功");
            }else {
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"上传失败");
            }
        }
    }


    /**
     * @author xieguo
     * 功能描述：excel导入，支持去重，批量更新
     * @param file
     * @return com.alibaba.fastjson.JSONObject
     * @date 2020/11/6 16:55
     */
    @ApiOperation(value = "不可移动文物excel导入")
    @PostMapping("/readImmovableExcel")
    public JSONObject readImmovableExcel(@RequestBody MultipartFile file){
        long t1 = System.currentTimeMillis();
        log.info("上传的文件："+file);
        //文件数据读入的集合
        List<ImmovableHistoricalRelics> readList = ExcelUtils.readExcel("readImmovableExcel",ImmovableHistoricalRelics.class, file);

        if (ObjectUtil.isEmpty(readList)){
            return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"excel导入格式有误");
        }

        //集合去重
        List<ImmovableHistoricalRelics> list = readList.stream().distinct().collect(Collectors.toList());

        //日期保留一位小数
        DecimalFormat format = new DecimalFormat("0.0");
        for (ImmovableHistoricalRelics relics : list) {
            if (StringUtils.isNotBlank(relics.getPublicationTime())){
                if (relics.getPublicationTime().length() > 40) {
                    relics.setPublicationTime(format.format(new BigDecimal(relics.getPublicationTime())));
                }
            }
        }

        int ihrpsBatchInsert = ihrps.handleList(list);

//        System.out.println("ihrpsBatchInsert=======================>"+ihrpsBatchInsert);

        // 获取集合对应的迭代器，用来遍历集合中的元素的。
//        list.removeIf(next -> null==next.getNumber());

        for (ImmovableHistoricalRelics relics : list) {
            if (StringUtils.isBlank(relics.getNumber())) {
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL, "文物编码不能为空");
            }
            if (StringUtils.isBlank(relics.getArea())){
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"行政区域不能为空");
            }
            if (StringUtils.isBlank(relics.getName())){
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"文物名称不能为空");
            }
//            if (StringUtils.isBlank(relics.getPeriod())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"文物期段不能为空");
//            }
//            if (StringUtils.isBlank(relics.getFoundingYear())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"始建年代不能为空");
//            }
//            if (StringUtils.isBlank(relics.getFormationPeriod())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"形成年代不能为空");
//            }
//            if (StringUtils.isBlank(relics.getReconstructionAge())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"复建年代不能为空");
//            }
//            if (StringUtils.isBlank(relics.getLevel())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"保护级别不能为空");
//            }
//            if (StringUtils.isBlank(relics.getAddress())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"地址不能为空");
//            }
//            if (StringUtils.isBlank(relics.getGpsLocation())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"经纬度不能为空");
//            }
//            if (StringUtils.isBlank(relics.getPreservationStatus())){
//                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"保存状况不能为空");
//            }
        }

//        System.out.println("sizeBefore========================>"+list.size());
        //数据库里面ImmovableHistoricalRelics表的集合
        List<ImmovableHistoricalRelics> relicsList = ihrm.selectList(null);
//        System.out.println("relicsList========================>"+relicsList.size());
        //文件数据重复数据的集合
        List<ImmovableHistoricalRelics> repeatData = new ArrayList<>();
        //文件重复数据更新的集合
        List<ImmovableHistoricalRelics> updateData = new ArrayList<>();

        //俩重循环筛选重复数据
        for (ImmovableHistoricalRelics historicalRelics : list) {

            for (ImmovableHistoricalRelics immovableHistoricalRelics : relicsList) {
                String number = historicalRelics.getNumber();
                String sqlNumber = immovableHistoricalRelics.getNumber();
                if (number.equals(sqlNumber)) {
                    repeatData.add(historicalRelics);
                    updateData.add(immovableHistoricalRelics);
                }
            }
        }

//        System.out.println(repeatData.size()+"==========="+updateData.size());

        //把录入的数据放入带有id的数据里面
        for (int i = 0; i <updateData.size() ; i++) {
            updateData.get(i).setNumber(repeatData.get(i).getNumber());
            updateData.get(i).setName(repeatData.get(i).getName());
            updateData.get(i).setType(repeatData.get(i).getType());
            updateData.get(i).setNature(repeatData.get(i).getNature());
            updateData.get(i).setPeriod(repeatData.get(i).getPeriod());
            updateData.get(i).setFoundingYear(repeatData.get(i).getFoundingYear());
            updateData.get(i).setFormationPeriod(repeatData.get(i).getFormationPeriod());
            updateData.get(i).setReconstructionAge(repeatData.get(i).getReconstructionAge());
            updateData.get(i).setLevel(repeatData.get(i).getLevel());
            updateData.get(i).setPublicationTime(repeatData.get(i).getPublicationTime());
            updateData.get(i).setPublicationNumber(repeatData.get(i).getPublicationNumber());
            updateData.get(i).setPropertyRights(repeatData.get(i).getPropertyRights());
            updateData.get(i).setAddress(repeatData.get(i).getAddress());
            updateData.get(i).setGpsLocation(repeatData.get(i).getGpsLocation());
            updateData.get(i).setPreservationStatus(repeatData.get(i).getPreservationStatus());
            updateData.get(i).setArea(repeatData.get(i).getArea());
            updateData.get(i).setPublicationBatch(repeatData.get(i).getPublicationBatch());
        }
//        System.out.println("repeatData=======================>"+repeatData.toString());
//        System.out.println("updateData=======================>"+updateData.toString());
        if (!updateData.isEmpty()){
            ihrm.batchUpdate(updateData);
        }

//        System.out.println("updateData===================>"+updateData.toString());
//        System.out.println("updateDataSize===================>"+updateData.size());

        list.removeAll(repeatData);

        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));

        if (list.isEmpty()){
            return Result.setResultByCodeAndMsg(Result.STATUS_SUCCESS,"数据已更新.");
        }else {
            int i = ihrm.batchInsert(list);

            if (i>0){
                return Result.setResultByCodeAndMsg(Result.STATUS_SUCCESS,"上传成功");
            }else {
                return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"上传失败");
            }
        }
    }

}
